package com.itheima.mongo;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.mongoservice.CommentsServiceApi;
import com.itheima.pojo.mongo.Comment;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class CommentsServiceApiImpl implements CommentsServiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Comment> getMovementComments(Integer page, Integer pagesize, String movementId) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType").is(2))
                .with(Sort.by(Sort.Order.desc("likeCount")))
                .skip((page-1)*pagesize).limit(pagesize);
//        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)));
        return mongoTemplate.find(query, Comment.class);
    }

    @Override
    public void comment(Comment comment) {
        mongoTemplate.save(comment);
    }

    @Override
    public boolean isExist(ObjectId id, String uid, int type) {
        Query query = Query.query(Criteria.where("publishId").is(id)
                .and("publishUserId").is(Convert.toLong(uid))
                .and("commentType").is(type));
        return mongoTemplate.exists(query, Comment.class);
    }

    @Override
    public void deleteComment(ObjectId id, String uid, int type) {
        Query query = Query.query(Criteria.where("publishId").is(id)
                .and("publishUserId").is(Convert.toLong(uid))
                .and("commentType").is(type));
        mongoTemplate.remove(query, Comment.class);
    }

    @Override
    public Long getCount(String messageID) {
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(messageID)).and("commentType").is(2));
        return mongoTemplate.count(query, Comment.class);
    }

    @Override
    public List<Comment> getComments(Long uid, int i) {
        Query query = Query.query(Criteria.where("userId").is(uid).and("commentType").is(i));
        return mongoTemplate.find(query, Comment.class);
    }

    @Override
    public Comment getById(ObjectId id) {
        return mongoTemplate.findOne(Query.query(Criteria.where("id").is(id)), Comment.class);
    }

    @Override
    public void updateLikeCount(ObjectId id, Boolean flag) {
        Comment comment = getById(id);
        if (ObjectUtil.isNull(comment)){
            return;
        }
        comment.setLikeCount(flag ? comment.getLikeCount() + 1 : comment.getLikeCount() - 1);
        mongoTemplate.save(comment);
    }
}
